# This file is part of the Net::Tube module.
#
# Net::Tube is Free Software; you can use, redistribute it and/or
# modify it under the terms of either:
#
# a) the GNU General Public License as published by the Free Software
#    Foundation, either version 2, or (at your opinion) any later
#    version, or
#
# b) the "Artistic License" which comes with Perl.
#
package Net::Tube::Filter::SimpleMerge;

use Net::Tube;
use XML::LibXML::Common qw(:libxml);
our @ISA = qw(Net::Tube::Filter);


sub merger_element {
    my $self = shift;
    my $me   = $self->get_config_entry('mergerElement');

    if ( defined $me and scalar @$me ) {
        if ( ref( $me->[0] ) =~ /^XML::LibXML::/ ) {
            my $c = {};
            foreach my $vnode ( $me->[0]->childNodes ) {
                next unless $vnode->nodeType == XML_ELEMENT_NODE;
                my $name = $vnode->localname;
                my $val  = $vnode->textContent;
                # warn "name = $name val = $val";
                $val =~ s/^\s*|\s*$//g;    
                $c->{$name} = $val;
            }
            $me->[0] = $c;
        }

        return $me->[0];
    }
    return undef;
}

sub bucket_merge {
    my $self      = shift;
    my $oldbucket = shift;
    my $bucket    = $self->create_bucket($oldbucket);

    if ( $oldbucket->count > 0 ) {
        my $doc = XML::LibXML->createDocument();
        $bucket->add_node($doc);

        my $ni = $self->merger_element;
        if ( defined $ni ) {
            my $name = $ni->{name};
            if ( defined $name && length $name ) {
                my $nsuri = $ni->{'namespace-uri'};
                my $nspre = $ni->{'namespace-prefix'};

                if ( defined $nsuri && length $nsuri ) {
                    if ( defined $nspre && length $nspre ) {
                        $name = $nspre . ":" . $name;
                    }
                }
                else {
                    $nsuri = "";
                }
                my $e = $doc->createElementNS( $nsuri, $name );
                $doc->setDocumentElement($e);

                my $nl = $oldbucket->node_list();
                foreach my $te ( $nl->get_nodelist() ) {
                    if ( $te->nodeType == XML_DOCUMENT_NODE ) {
                        $e->appendChild(
                            $doc->adoptNode( $te->documentElement ) );
                    }
                    else {
                        $e->appendChild( $doc->adoptNode($te) );
                    }
                }
            }
        }
    }

    return $bucket;
}

sub process {
    my $self   = shift;
    my $bucket = $self->SUPER::process(@_);
    return $self->bucket_merge($bucket);
}

1;
